﻿using Aliyun.OSS;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using MiniX.API.Controllers;
using MiniX.API.Data;
using MiniX.Utility.Helper;
using MiniX.API.Filters;

namespace TWZDTT.API.Controllers
{
    /// <summary>
    /// 上传图片
    /// </summary>
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UploadController : BaseController<UploadController>
    {
        /// <summary>
        /// UploadController
        /// </summary>
        public UploadController(MiniXApiContext context, IHttpContextAccessor httpContextAccessor) : base(context, httpContextAccessor)
        {

        }

        /// <summary>
        /// 上传文件或图片至阿里云OSS
        /// </summary>
        /// <returns></returns>
        [Route("/api/upload")]
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> UploadImg()
        {
            var files = Request.Form.Files;
            var formFile = files[0];
            var fileName = formFile.FileName;
            var saveDir = MiniX.API.Filters.AppSettingsFilter.GetSetting("Upload:PATH");
            var tempPath = saveDir + "\\" + DateTime.Now.Year + "\\" + DateTime.Now.ToString("MMdd") + "\\";
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            var extension = ".png";
            var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + MiniX.Utility.Helper.CommonHelper.GenerateRandomNum(6);
            var savePath = tempPath + newFileName + extension;
            var returnPath = "/" + DateTime.Now.Year + "/" + DateTime.Now.ToString("MMdd") + "/" + newFileName + extension;

            try
            {
                if (!Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }
                if (System.IO.File.Exists(savePath))
                {
                    System.IO.File.Delete(savePath);
                }
                using (FileStream fs = System.IO.File.Create(savePath))
                {
                    await formFile.CopyToAsync(fs);
                    fs.Flush();
                    fs.Close();
                }

                // 上传至OSS
                try
                {
                    using FileStream fi = new FileStream(savePath, FileMode.Open);
                    OssClient client = new OssClient(MiniX.Utility.Config.AliyunOSS.Endpoint, MiniX.Utility.Config.AliyunOSS.AccessKeyId, MiniX.Utility.Config.AliyunOSS.AccessKeySecret);
                    var key = "upload/" + DateTime.Now.Year + "/" + DateTime.Now.ToString("MMdd") + "/";
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        client.PutObject(MiniX.Utility.Config.AliyunOSS.BucketName, key, memStream);
                    }

                    ObjectMetadata metadata = new ObjectMetadata();
                    metadata.ContentType = Request.Form.Files[0].ContentType;
                    client.PutObject(MiniX.Utility.Config.AliyunOSS.BucketName, key + newFileName + extension, fi, metadata);
                }
                catch (Exception ex)
                {
                    log.Fatal(ex, " -> 上传至OSS");
                }

                return Json(new { code = 0, msg = "上传成功", path = "/upload" + returnPath, returnPath, name = newFileName, data = new { src = DataFilter.GetSettingInfoValue(_context, log, (int)ENUMHelper.SettingInfoType.AliyunCallbackServer) + "/upload" + returnPath, title = "" } });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Create, errmsg = ex.Message });
            }
        }
    }
}
